package org.dingfugui.triple.protocol.binary.aio;

import org.dingfugui.triple.common.Logger;
import org.dingfugui.triple.common.LoggerFactory;
import org.dingfugui.triple.protocol.RequestHandler;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * Created by fugui.ding on 2015/4/20.
 */
public class AioProducerConnection {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    final AsynchronousSocketChannel socket;
    private final AioDataReader dataReader;
    private final AioDataWriter dataWriter;
    private final RequestHandler handler;

    public AioProducerConnection(AsynchronousSocketChannel socket, RequestHandler handler) {
        this.socket = socket;
        this.handler = handler;
        this.dataReader = new AioDataReader(this);
        this.dataWriter = new AioDataWriter(this);
    }

    public void read(final AioReader reader) {
        ByteBuffer bb = reader.getBuffer();

        socket.read(bb, bb, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer bb) {
                if (result < 0) {
                    //报错
                } else if (result > 0) {
                    dataReader.onData(bb, result);
                }
                reader.run();
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                logger.error("读取数据异常", exc);
            }
        });
    }

    public void write(byte[] data) {
        logger.trace("返回数据:{}", data.length);
        dataWriter.writeData(data);
    }

    public void handle(byte[] data) {
        logger.trace("处理数据:{}", data.length);
        byte[] result = handler.handleRequest(data);
        write(result);
    }
}
